package com.web.my12306.dao.impl;


import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.*;

/**
 * 郭明亮
 * 2017/09/12
 * 11:13
 * 行37,帐号密码自己改！
 */
public class BaseDao
{
    protected Connection conn = null;
    protected PreparedStatement ps = null;
    protected ResultSet rs = null;

    //加载驱动
    static
    {
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e)
        {
            e.printStackTrace();
        }
    }

    //获取连接
    private void getConnection()
    {
        try {
            Context context = new InitialContext();
            DataSource datasource = (DataSource)context.lookup("java:comp/env/jdbc/My12306");
            conn = datasource.getConnection();
        } catch (NamingException | SQLException e) {
            e.printStackTrace();
        }
    }

    //关闭连接
    protected void closeAll()
    {
        if (rs != null)
            try
            {
                rs.close();
            } catch (SQLException e)
            {
                e.printStackTrace();
            }
        if (ps != null)
            try
            {
                ps.close();
            } catch (SQLException e)
            {
                e.printStackTrace();
            }
        if (conn != null)
            try
            {
                conn.close();
            } catch (SQLException e)
            {
                e.printStackTrace();
            }
    }

    //查询
    public ResultSet query(String sql, Object... params)
    {
        rs = null;
        try
        {
            getConnection();
            ps = conn.prepareStatement(sql);
            for (int i = 0; i < params.length; i++)
            {
                ps.setObject(i + 1, params[i]);
            }
            rs = ps.executeQuery();
        } catch (SQLException e)
        {
            e.printStackTrace();
        }
        return rs;
    }

    //增删改
    public void update(String sql, Object... params)
    {
        try
        {
            getConnection();
            ps = conn.prepareStatement(sql);
            for (int i = 0; i < params.length; i++)
            {
                ps.setObject(i + 1, params[i]);
            }
            ps.executeUpdate();
        } catch (SQLException e)
        {
            e.printStackTrace();
        } finally
        {
            closeAll();
        }
    }
}
